package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.base.service.daoimpl.BaseServiceImpl;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.HealthRecordStatusEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.DiseaseInfoDao;
import com.frogs.ucenter.entity.DiseaseInfo;
import com.frogs.ucenter.v1.request.DiseaseInfoListRequest;
import com.frogs.ucenter.v1.request.DiseaseInfoMergeRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.response.ListResponse;
import com.frogs.ucenter.v1.service.DiseaseInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"diseaseInfoService")
public class DiseaseInfoServiceImpl extends BaseServiceImpl<DiseaseInfo> implements DiseaseInfoService{

	private static final Logger log = LoggerFactory.getLogger(DiseaseInfoServiceImpl.class);
	
	@Resource
	private DiseaseInfoDao diseaseInfoDao;
	
	/**
	 * 添加或修改疾病档案
	 */
	@Override
	public Response mergeRecord(Request request) throws Exception {
		AddResponse<DiseaseInfo> response = new AddResponse<DiseaseInfo>();
		try {
			DiseaseInfoMergeRequest diMergeRequest = (DiseaseInfoMergeRequest)request;
			DiseaseInfo diseaseInfo = new DiseaseInfo();
			Integer id = diMergeRequest.getId();
			Integer userId = diMergeRequest.getUserId();
			String diseaseName = diMergeRequest.getDiseaseName();
			diseaseInfo.setUserId(userId);
			diseaseInfo.setOccurrenceTime(DateUtil.parseDate(diMergeRequest.getOccurrenceTime(),"yyyy-MM-dd HH:mm:ss"));
			diseaseInfo.setCreateTime(DateUtil.parseDate(diMergeRequest.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
			diseaseInfo.setUpdateTime(new Date());
			diseaseInfo.setDiseaseName(diseaseName);
			if(id < 1){//新建一条档案
				//插入新的档案
				diseaseInfo.setStatus(diMergeRequest.getStatus());
				diseaseInfoDao.insert(diseaseInfo);
				response.setInfo(diseaseInfo);
				response.setTip("疾病档案添加成功");
			}else{//更新档案
				String oldDiseaseName = diseaseInfoDao.selectById(id).getDiseaseName();
				if(oldDiseaseName.equals(diseaseName)){//疾病名字没有改变
					diseaseInfo.setId(id);
					diseaseInfo.setStatus(HealthRecordStatusEnum.YES.getId());
					diseaseInfoDao.update(diseaseInfo);
					response.setInfo(diseaseInfo);
					response.setTip("疾病档案更新成功");
				}else{//疾病名字发生改变
					//将之前档案的状态改变
					Map<String,Object> params = new HashMap<String,Object>();
					params.clear();
					params.put("eqId", id);
					params.put("eaUserId", userId);
					params.put("eqStatus", HealthRecordStatusEnum.YES.getId());
					params.put("status", HealthRecordStatusEnum.NO.getId());
					diseaseInfoDao.updateByMap(params);
					//插入新的档案
					diseaseInfo.setStatus(HealthRecordStatusEnum.YES.getId());
					diseaseInfoDao.insert(diseaseInfo);
					
					response.setInfo(diseaseInfo);
					response.setTip("疾病档案更新成功");
				}
			}
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response listRecord(Request request) throws Exception {
		ListResponse<DiseaseInfo> response = new ListResponse<DiseaseInfo>();
		try {
			DiseaseInfoListRequest diListRequest = (DiseaseInfoListRequest)request;
			Integer pageNo = diListRequest.getPageNo();
			Integer pageSize = diListRequest.getPageSize();
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("eqUserId", diListRequest.getUserId());
			params.put("eqStatus", diListRequest.getStatus());
			params.put("orderByClause", "update_time desc");
			PageList<DiseaseInfo> list = new PageList<DiseaseInfo>();
			list = diseaseInfoDao.selectByMap(params, pageNo, pageSize);
			response.setList(list);
			response.setTip("疾病档案查询成功");
			
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

	@Override
	public Response deleteRecord(Request request) throws Exception {
		AddResponse<DiseaseInfo> response = new AddResponse<DiseaseInfo>();
		try {
			DiseaseInfoMergeRequest diMergeRequest = (DiseaseInfoMergeRequest)request;
			DiseaseInfo diseaseInfo = new DiseaseInfo();
			Integer id = diMergeRequest.getId();
			Integer userId = diMergeRequest.getUserId();
			String diseaseName = diMergeRequest.getDiseaseName();
			diseaseInfo.setUserId(userId);
			diseaseInfo.setOccurrenceTime(DateUtil.parseDate(diMergeRequest.getOccurrenceTime(),"yyyy-MM-dd HH:mm:ss"));
			diseaseInfo.setCreateTime(DateUtil.parseDate(diMergeRequest.getCreateTime(),"yyyy-MM-dd HH:mm:ss"));
			diseaseInfo.setUpdateTime(new Date());
			diseaseInfo.setDiseaseName(diseaseName);
			diseaseInfo.setId(id);
			diseaseInfo.setStatus(HealthRecordStatusEnum.NO.getId());
			diseaseInfoDao.update(diseaseInfo);
			
			response.setInfo(diseaseInfo);
			response.setTip("疾病档案删除成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
			throw new ServiceOperationException("请求处理失败：" + e.getMessage());
		}
		return response;
	}

}
